package migranitodejava.introduccion;

import java.util.Properties;

import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;

public class SessionManager {

	public static Session getSession() throws HibernateException {

		Configuration config = new Configuration();

		registerMappers(config);

		config.setProperties(getHibernateProperties());
		
		new SchemaExport(config).create(false, true);

		return config.buildSessionFactory().openSession(); // Retorna una sesion de trabajo
	}

	private static Properties getHibernateProperties() {

		Properties props = new Properties();
		props.put("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
		props.put("hibernate.connection.url", "jdbc:mysql://localhost/hibernate_tests_mgdj");
		props.put("hibernate.connection.username", "root");
		props.put("hibernate.connection.password", "passw0rd");
		props.put("hibernate.hbm2ddl.auto", "create");
		props.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");

		return props;
	}

	private static void registerMappers(Configuration config) throws MappingException {
		config.addResource("migranitodejava/introduccion/Auto.hbm.xml");
	}
}
